﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

using QuickShot.Windows;

namespace QuickShot.Utility
{
    public sealed class ScreenCapture
    {

        public static void SaveCapture(Bitmap capture, string location, ImageFormat format)
        {
            capture.Save(location + @"\capture." + Enum.GetName(typeof(ImageFormat), format), MapFormat(format));
        }

        public static Bitmap CaptureScreen(Point point, Size size)
        {
            Bitmap bmp = null;
            IntPtr hDwin = WinAPI.GetDesktopWindow();
            IntPtr hSrc = WinAPI.GetWindowDC(hDwin);
            IntPtr hDest = WinAPI.CreateCompatibleDC(hSrc);
            IntPtr hBmp = WinAPI.CreateCompatibleBitmap(hSrc, size.Width, size.Height);
            IntPtr oldBitmap = WinAPI.SelectObject(hDest, hBmp);
            WinAPI.BitBlt(hDest, 0, 0, size.Width, size.Height, hSrc, point.X, point.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
            bmp = Bitmap.FromHbitmap(hBmp);
            WinAPI.SelectObject(hDest, oldBitmap);
            WinAPI.DeleteDC(hDest);
            WinAPI.ReleaseDC(hDwin, hSrc);
            return bmp;
        }

        private static System.Drawing.Imaging.ImageFormat MapFormat (ImageFormat format)
        {
            if (format == ImageFormat.Png)
                return System.Drawing.Imaging.ImageFormat.Png;

            if (format == ImageFormat.Jpeg)
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            
            return System.Drawing.Imaging.ImageFormat.Bmp;
        }
    }
}
